package com.ihunanren.biz.function;

import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import com.google.common.base.Throwables;
import com.ihunanren.common.CollectionUtils;

/**
 * @author kalman03
 */
public class Http {

	enum HttpMethod{
		get,post
	}
	
	private final HttpClient httpclient;
	/**
	 * @param connectionTimeout 设置连接的超时时间
	 * @param soTimeout 设置读取数据的超时时间
	 */
	public Http(int connectionTimeout, int soTimeout) {
		httpclient = new DefaultHttpClient();
		httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout);
		httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout);
	}
	
	/**
	 * 连接超时与读取数据超时时间默认为2000ms
	 */
	public Http(){
		this(2000, 2000);
	}

	public String doGetAsString(String uri, Map<String, ? extends Object> param) {
		try {
			HttpResponse response = doClient(uri, param, HttpMethod.get);
			if(response == null)return null;
			HttpEntity entity =  response.getEntity();
			return EntityUtils.toString(entity);
		} catch (Exception e) {
			Throwables.propagate(e);
		}
		return null;

	}

	public InputStream doGetAsInputStream(String uri, Map<String, ? extends Object> param){
		try {
			HttpResponse response = doClient(uri, param, HttpMethod.get);
			if(response == null)return null;
			return response.getEntity().getContent();
		} catch (Exception e) {
			Throwables.propagate(e);
		}
		return null;
	}
	
	
	public  byte[]  doGetAsByte(String uri, Map<String, ? extends Object> param){
		try {
			HttpResponse response = doClient(uri, param, HttpMethod.get);
			if(response == null)return null;
			HttpEntity entity =  response.getEntity();
			return EntityUtils.toByteArray(entity);
		} catch (Exception e) {
			Throwables.propagate(e);
		}
		return null;
	}
	
	@SuppressWarnings("deprecation")
	private HttpResponse doClient(String uri,Map<String,  ? extends Object> param,HttpMethod method) throws Exception{
		HttpResponse response = null;
		if (method == HttpMethod.get) {
			StringBuilder sb = new StringBuilder();
			sb.append(uri).append("?");
			if(CollectionUtils.isNotEmpty(param)){
				for (Entry<String, ? extends Object> entry : param.entrySet()) {
					String value = URLEncoder.encode("" + entry.getValue(), "utf-8");
					sb.append(entry.getKey()).append("=").append(value).append("&");
				}
			}
			HttpGet request = new HttpGet(sb.toString());
			response =  httpclient.execute(request);
		} else {
			List<BasicNameValuePair>   nvps = new ArrayList<BasicNameValuePair>(); 
			if(CollectionUtils.isNotEmpty(param)){
				for (Entry<String, ? extends Object> entry : param.entrySet()) {
					if(entry.getValue() != null)
					 nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString())); 
				}
			}
			HttpPost request = new HttpPost(uri);
			
			request.setEntity(new UrlEncodedFormEntity(nvps,HTTP.UTF_8));
			response = httpclient.execute(request);
		}
		if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
			return response;
		}
		return null;
	}
}
